package com.treasure.service.wechat.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.treasure.service.annotation.LogInfo;
import com.treasure.service.annotation.NoLogin;
import com.treasure.service.commons.lang.util.BeanUtil;
import com.treasure.service.commons.lang.util.StringUtil;
import com.treasure.service.constant.GlobalConstant;
import com.treasure.service.domain.AccessToken;
import com.treasure.service.dto.TUserInfoDto;
import com.treasure.service.enums.CodeEnum;
import com.treasure.service.third.utils.*;
import com.treasure.service.result.ResponseResult;
import com.treasure.service.user.service.UserService;
import com.treasure.service.wechat.common.WxUser;
import com.treasure.service.wechat.service.WechatService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

/**
 * @author <a href="mailto:125671254@qq.com">Pan Xinwen</a>panxinwen
 * @ClassName: WechatController
 * @Description: TODO(公众号交互相关)
 * @date 2018年5月29日 下午21:47:59
 */
@RestController
public class WechatController {
    private Logger log = LoggerFactory.getLogger(WechatController.class);
    @Autowired
    private WechatService wechatService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${treasure.wx.appId}")
    private String appId;

    /**
     * 获取js sdk 认证信息
     *
     * @param
     * @return
     * @author
     */
    @SuppressWarnings("rawtypes")
    @LogInfo(log = "jssdk分享认证")
    @NoLogin
    @ApiOperation(value = "jssdk分享认证", notes = "v1")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "query", dataType = "String", name = "url", value = "待签名url", required = true)
    })
    @RequestMapping(value = "/getSign", method = {RequestMethod.GET, RequestMethod.POST})
    public String getSign(@RequestParam(value = "url", required = true) String url) throws UnsupportedEncodingException {
        url = URLDecoder.decode(url, GlobalConstant.ENCODING_UTF8);
        log.info("校验签名的url============" + url);
        //获取ticket
        AccessToken accessToken = wechatService.getAccess_token();
        Map<String, String> ret = Sign.sign(accessToken.getJsapiTicket(), url);
        log.info("计算出的签名：" + ret.toString());
        JSONObject json = new JSONObject();
        for (Map.Entry entry : ret.entrySet()) {
            log.info((entry.getKey() + "=============" + entry.getValue()));
            json.put(entry.getKey().toString(), entry.getValue());
        }

        log.info("分享出去的url====" + url);

        json.put("shareUrl", url);
        json.put("appId", appId);

        return json.toString();
    }


    // 微信授权回调地址
    @NoLogin
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    @LogInfo(log = "微信授权登录")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "String", name = "code", value = "授权登录后微信返回兑换码", required = true),
            @ApiImplicitParam(paramType = "query", dataType = "int", name = "platform", value = "平台类型(1-web 2-wechat 3-Android 4-ios 5-wap)", required = true)
    })
    public ResponseEntity login(@RequestParam(value = "code") String code,
                      @RequestParam(value = "platform") int platform) throws UnsupportedEncodingException {
        WxUser wxUser = wechatService.redirect(code);
        String opendId = wxUser.getOpenid();
        String access_token = wxUser.getAccess_token();
        log.info("获取用户基本信息：" + JSON.toJSONString(wxUser));
        wxUser = wechatService.wxUserInfo(opendId, access_token);

        //查询是否存在该用户
        TUserInfoDto user = userService.getUserInfoByUnionid(wxUser.getUnionid());

        UserToken token =null;
        if (user == null|| StringUtil.isEmpty(user.getUserId())) {
            log.info("获取用户微信信息：" + JSON.toJSONString(wxUser));
            //创建新用户
            user = new TUserInfoDto();
//            user.setOpenId(opendId);
            user.setUnionid(wxUser.getUnionid());
            user.setNickname(wxUser.getNickname());
            user.setWNickname(wxUser.getNickname());
            user.setHeadimgurl(wxUser.getHeadimgurl());
            user.setWHeadimgurl(wxUser.getHeadimgurl());
            user.setPlatform(platform);
            user = userService.createWechatUser(user);
            log.info("创建用户息：" + JSON.toJSONString(user));
            token = BeanUtil.copy(user, UserToken::new);
        } else {
            Long userId = user.getUserId();
            user = new TUserInfoDto();
            user.setUserId(userId);
            user.setNickname(wxUser.getNickname());
            user.setHeadimgurl(wxUser.getHeadimgurl());
            user=userService.updateUserInfo(user);
            log.info("更新用户：" + JSON.toJSONString(user));
            token = BeanUtil.copy(user, UserToken::new);
        }
        token = TokenConfig.addToken(token);
        TokenConfig.setAttribute(SessionKey.TOKEN,token.getTokenId());

        return ResponseEntity.ok(new ResponseResult(CodeEnum.SUCCESS,token));

    }

    // 微信授权回调地址
    @NoLogin
    @RequestMapping(value = "/testlogin", method = {RequestMethod.POST})
    @LogInfo(log = "微信授权登录")
    public ResponseEntity testlogin() throws UnsupportedEncodingException {

        TUserInfoDto user = new TUserInfoDto();
//        user.setUserId(201843505976420101l);
        user.setNickname("î\\u0080\\u0083ç\\u0090ªç\\u0090ª Â¹Â³â\\u0082\\u0081â\\u0082\\u0084");
        user.setHeadimgurl("http://thirdwx.qlogo.cn/mmopen/vi_32/GkxYERPDdTMwiacKA17GEIAcmSBpib0GokALqP2FJbhmfic5kq7xtJauDkCcJV8Dyo453QZiciaXq5luBF14txEV6wA/132");
        userService.updateUserInfo(user);
        log.info("更新用户：" + JSON.toJSONString(user));

        return ResponseEntity.ok(new ResponseResult(CodeEnum.SUCCESS,""));

    }



    @NoLogin
    @LogInfo(log = "获取二维码")
    @ApiOperation(value = "生成用户推广二维码", notes = "v1")
    @PostMapping(value = "/getQRCode")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataType = "Integer", name = "type", value = "分享图片地址（1-邀请办卡 2-邀请会员 3-邀请贷款）", required = true),
    })
    public ResponseEntity getQRCode(@RequestParam(value = "type", required = true) Integer type){

        UserToken userToken = TokenConfig.getTokenByHeader();

        String QRCode = wechatService.createShareImg(type,userToken.getSelfInviteCode());

        String last = "_invitecard.jpg?v=213";
        if (type == 1){

            last="_invitecard.jpg?v=213";
        }else if (type == 2){
            last="_invitevip.jpg?v=213";
        }else {
            last="_inviteLoans.jpg?v=213";
        }

        return ResponseEntity.ok(new ResponseResult(CodeEnum.SUCCESS,"http://floor.jingyugg.com/"+userToken.getSelfInviteCode()+last));
    }

}
